1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package com.opensymphony.xwork2.util;
20
21 import org.apache.logging.log4j.Logger;
22 import org.apache.logging.log4j.LogManager;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.lang.annotation.Annotation;
28 import java.net.URL;
29 import java.net.URLDecoder;
30 import java.util.Enumeration;
31 import java.util.HashSet;
32 import java.util.Set;
33 import java.util.jar.JarEntry;
34 import java.util.jar.JarInputStream;
35
36 /**
37 * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
38 * arbitrary conditions. The two most common conditions are that a class implements/extends
39 * another class, or that is it annotated with a specific annotation. However, through the use
40 * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
41 *
42 * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
43 * path that contain classes within certain packages, and then to load those classes and
44 * check them. By default the ClassLoader returned by
45 * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
46 * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
47 * methods.</p>
48 *
49 * <p>General searches are initiated by calling the
50 * {@link #find(com.opensymphony.xwork2.util.ResolverUtil.Test, String...)} ()} method and supplying
51 * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
52 * to be scanned for classes that meet the test. There are also utility methods for the common
53 * use cases of scanning multiple packages for extensions of particular classes, or classes
54 * annotated with a specific annotation.</p>
55 *
56 * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
57 *
58 *<pre>
59 *ResolverUtil<ActionBean> resolver = new ResolverUtil<ActionBean>();
60 *resolver.findImplementation(ActionBean.class, pkg1, pkg2);
61 *resolver.find(new CustomTest(), pkg1);
62 *resolver.find(new CustomTest(), pkg2);
63 *Collection<ActionBean> beans = resolver.getClasses();
64 *</pre>
65 *
66 * <p>This class was copied from Stripes - http://stripes.mc4j.org/confluence/display/stripes/Home</p>
67 *
68 * @author Tim Fennell
69 */
70 public class ResolverUtil<T> {
71 /** An instance of Log to use for logging in this class. */
72 private static final Logger LOG = LogManager.getLogger(ResolverUtil.class);
73
74 /**
75 * A simple interface that specifies how to test classes to determine if they
76 * are to be included in the results produced by the ResolverUtil.
77 */
78 public static interface Test {
79 /**
80 * Will be called repeatedly with candidate classes.
81 *
82 * @param type class type
83 * @return True if a class is to be included in the results, false otherwise.
84 */
85 boolean matches(Class type);
86
87 boolean matches(URL resource);
88
89 boolean doesMatchClass();
90 boolean doesMatchResource();
91 }
92
93 public static abstract class ClassTest implements Test {
94 public boolean matches(URL resource) {
95 throw new UnsupportedOperationException();
96 }
97
98 public boolean doesMatchClass() {
99 return true;
100 }
101 public boolean doesMatchResource() {
102 return false;
103 }
104 }
105
106 public static abstract class ResourceTest implements Test {
107 public boolean matches(Class cls) {
108 throw new UnsupportedOperationException();
109 }
110
111 public boolean doesMatchClass() {
112 return false;
113 }
114 public boolean doesMatchResource() {
115 return true;
116 }
117 }
118
119 /**
120 * A Test that checks to see if each class is assignable to the provided class. Note
121 * that this test will match the parent type itself if it is presented for matching.
122 */
123 public static class IsA extends ClassTest {
124 private Class parent;
125
126 /** Constructs an IsA test using the supplied Class as the parent class/interface.
127 * @param parentType the parent type class
128 */
129 public IsA(Class parentType) { this.parent = parentType; }
130
131 /**
132 * @param type class type
133 * @return true if type is assignable to the parent type supplied in the constructor.
134 */
135 public boolean matches(Class type) {
136 return type != null && parent.isAssignableFrom(type);
137 }
138
139 @Override public String toString() {
140 return "is assignable to " + parent.getSimpleName();
141 }
142 }
143
144 /**
145 * A Test that checks to see if each class name ends with the provided suffix.
146 */
147 public static class NameEndsWith extends ClassTest {
148 private String suffix;
149
150 /**
151 * Constructs a NameEndsWith test using the supplied suffix.
152 * @param suffix suffix
153 */
154 public NameEndsWith(String suffix) { this.suffix = suffix; }
155
156 /**
157 * @param type class type
158 * @return true if type name ends with the suffix supplied in the constructor.
159 */
160 public boolean matches(Class type) {
161 return type != null && type.getName().endsWith(suffix);
162 }
163
164 @Override public String toString() {
165 return "ends with the suffix " + suffix;
166 }
167 }
168
169 /**
170 * A Test that checks to see if each class is annotated with a specific annotation. If it
171 * is, then the test returns true, otherwise false.
172 */
173 public static class AnnotatedWith extends ClassTest {
174 private Class<? extends Annotation> annotation;
175
176 /**
177 * Constructs an AnnotatedWith test for the specified annotation type.
178 *
179 * @param annotation annotation
180 */
181 public AnnotatedWith(Class<? extends Annotation> annotation) { this.annotation = annotation; }
182
183 /**
184 * @param type class type
185 * @return true if the type is annotated with the class provided to the constructor.
186 */
187 public boolean matches(Class type) {
188 return type != null && type.isAnnotationPresent(annotation);
189 }
190
191 @Override public String toString() {
192 return "annotated with @" + annotation.getSimpleName();
193 }
194 }
195
196 public static class NameIs extends ResourceTest {
197 private String name;
198
199 public NameIs(String name) { this.name = "/" + name; }
200
201 public boolean matches(URL resource) {
202 return (resource.getPath().endsWith(name));
203 }
204
205 @Override public String toString() {
206 return "named " + name;
207 }
208 }
209
210 /** The set of matches being accumulated. */
211 private Set<Class<? extends T>> classMatches = new HashSet<Class<?extends T>>();
212
213 /** The set of matches being accumulated. */
214 private Set<URL> resourceMatches = new HashSet<>();
215
216 /**
217 * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
218 * by Thread.currentThread().getContextClassLoader() will be used.
219 */
220 private ClassLoader classloader;
221
222 /**
223 * Provides access to the classes discovered so far. If no calls have been made to
224 * any of the {@code find()} methods, this set will be empty.
225 *
226 * @return the set of classes that have been discovered.
227 */
228 public Set<Class<? extends T>> getClasses() {
229 return classMatches;
230 }
231
232 public Set<URL> getResources() {
233 return resourceMatches;
234 }
235
236
237 /**
238 * Returns the classloader that will be used for scanning for classes. If no explicit
239 * ClassLoader has been set by the calling, the context class loader will be used.
240 *
241 * @return the ClassLoader that will be used to scan for classes
242 */
243 public ClassLoader getClassLoader() {
244 return classloader == null ? Thread.currentThread().getContextClassLoader() : classloader;
245 }
246
247 /**
248 * Sets an explicit ClassLoader that should be used when scanning for classes. If none
249 * is set then the context classloader will be used.
250 *
251 * @param classloader a ClassLoader to use when scanning for classes
252 */
253 public void setClassLoader(ClassLoader classloader) { this.classloader = classloader; }
254
255 /**
256 * Attempts to discover classes that are assignable to the type provided. In the case
257 * that an interface is provided this method will collect implementations. In the case
258 * of a non-interface class, subclasses will be collected. Accumulated classes can be
259 * accessed by calling {@link #getClasses()}.
260 *
261 * @param parent the class of interface to find subclasses or implementations of
262 * @param packageNames one or more package names to scan (including subpackages) for classes
263 */
264 public void findImplementations(Class parent, String... packageNames) {
265 if (packageNames == null) return;
266
267 Test test = new IsA(parent);
268 for (String pkg : packageNames) {
269 findInPackage(test, pkg);
270 }
271 }
272
273 /**
274 * Attempts to discover classes who's name ends with the provided suffix. Accumulated classes can be
275 * accessed by calling {@link #getClasses()}.
276 *
277 * @param suffix The class name suffix to match
278 * @param packageNames one or more package names to scan (including subpackages) for classes
279 */
280 public void findSuffix(String suffix, String... packageNames) {
281 if (packageNames == null) return;
282
283 Test test = new NameEndsWith(suffix);
284 for (String pkg : packageNames) {
285 findInPackage(test, pkg);
286 }
287 }
288
289 /**
290 * Attempts to discover classes that are annotated with to the annotation. Accumulated
291 * classes can be accessed by calling {@link #getClasses()}.
292 *
293 * @param annotation the annotation that should be present on matching classes
294 * @param packageNames one or more package names to scan (including subpackages) for classes
295 */
296 public void findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
297 if (packageNames == null) return;
298
299 Test test = new AnnotatedWith(annotation);
300 for (String pkg : packageNames) {
301 findInPackage(test, pkg);
302 }
303 }
304
305 public void findNamedResource(String name, String... pathNames) {
306 if (pathNames == null) return;
307
308 Test test = new NameIs(name);
309 for (String pkg : pathNames) {
310 findInPackage(test, pkg);
311 }
312 }
313
314 /**
315 * Attempts to discover classes that pass the test. Accumulated
316 * classes can be accessed by calling {@link #getClasses()}.
317 *
318 * @param test the test to determine matching classes
319 * @param packageNames one or more package names to scan (including subpackages) for classes
320 */
321 public void find(Test test, String... packageNames) {
322 if (packageNames == null) return;
323
324 for (String pkg : packageNames) {
325 findInPackage(test, pkg);
326 }
327 }
328
329 /**
330 * Scans for classes starting at the package provided and descending into subpackages.
331 * Each class is offered up to the Test as it is discovered, and if the Test returns
332 * true the class is retained. Accumulated classes can be fetched by calling
333 * {@link #getClasses()}.
334 *
335 * @param test an instance of {@link Test} that will be used to filter classes
336 * @param packageName the name of the package from which to start scanning for
337 * classes, e.g. {@code net.sourceforge.stripes}
338 */
339 public void findInPackage(Test test, String packageName) {
340 packageName = packageName.replace('.', '/');
341 ClassLoader loader = getClassLoader();
342 Enumeration<URL> urls;
343
344 try {
345 urls = loader.getResources(packageName);
346 }
347 catch (IOException ioe) {
348 if (LOG.isWarnEnabled()) {
349 LOG.warn("Could not read package: " + packageName, ioe);
350 }
351 return;
352 }
353
354 while (urls.hasMoreElements()) {
355 try {
356 String urlPath = urls.nextElement().getFile();
357 urlPath = URLDecoder.decode(urlPath, "UTF-8");
358
359 // If it's a file in a directory, trim the stupid file: spec
360 if ( urlPath.startsWith("file:") ) {
361 urlPath = urlPath.substring(5);
362 }
363
364 // Else it's in a JAR, grab the path to the jar
365 if (urlPath.indexOf('!') > 0) {
366 urlPath = urlPath.substring(0, urlPath.indexOf('!'));
367 }
368
369 if (LOG.isInfoEnabled()) {
370 LOG.info("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
371 }
372 File file = new File(urlPath);
373 if ( file.isDirectory() ) {
374 loadImplementationsInDirectory(test, packageName, file);
375 }
376 else {
377 loadImplementationsInJar(test, packageName, file);
378 }
379 }
380 catch (IOException ioe) {
381 if (LOG.isWarnEnabled()) {
382 LOG.warn("could not read entries", ioe);
383 }
384 }
385 }
386 }
387
388
389 /**
390 * Finds matches in a physical directory on a filesystem. Examines all
391 * files within a directory - if the File object is not a directory, and ends with <i>.class</i>
392 * the file is loaded and tested to see if it is acceptable according to the Test. Operates
393 * recursively to find classes within a folder structure matching the package structure.
394 *
395 * @param test a Test used to filter the classes that are discovered
396 * @param parent the package name up to this directory in the package hierarchy. E.g. if
397 * /classes is in the classpath and we wish to examine files in /classes/org/apache then
398 * the values of <i>parent</i> would be <i>org/apache</i>
399 * @param location a File object representing a directory
400 */
401 private void loadImplementationsInDirectory(Test test, String parent, File location) {
402 File[] files = location.listFiles();
403 StringBuilder builder = null;
404
405 for (File file : files) {
406 builder = new StringBuilder(100);
407 builder.append(parent).append("/").append(file.getName());
408 String packageOrClass = ( parent == null ? file.getName() : builder.toString() );
409
410 if (file.isDirectory()) {
411 loadImplementationsInDirectory(test, packageOrClass, file);
412 }
413 else if (isTestApplicable(test, file.getName())) {
414 addIfMatching(test, packageOrClass);
415 }
416 }
417 }
418
419 private boolean isTestApplicable(Test test, String path) {
420 return test.doesMatchResource() || path.endsWith(".class") && test.doesMatchClass();
421 }
422
423 /**
424 * Finds matching classes within a jar files that contains a folder structure
425 * matching the package structure. If the File is not a JarFile or does not exist a warning
426 * will be logged, but no error will be raised.
427 *
428 * @param test a Test used to filter the classes that are discovered
429 * @param parent the parent package under which classes must be in order to be considered
430 * @param jarfile the jar file to be examined for classes
431 */
432 private void loadImplementationsInJar(Test test, String parent, File jarfile) {
433 try(JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile))) {
434 JarEntry entry;
435 while ((entry = jarStream.getNextJarEntry() ) != null) {
436 String name = entry.getName();
437 if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
438 addIfMatching(test, name);
439 }
440 }
441 } catch (IOException ioe) {
442 LOG.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " +
443 test + " due to an IOException", ioe);
444 }
445 }
446
447 /**
448 * Add the class designated by the fully qualified class name provided to the set of
449 * resolved classes if and only if it is approved by the Test supplied.
450 *
451 * @param test the test used to determine if the class matches
452 * @param fqn the fully qualified name of a class
453 */
454 protected void addIfMatching(Test test, String fqn) {
455 try {
456 ClassLoader loader = getClassLoader();
457 if (test.doesMatchClass()) {
458 String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
459 if (LOG.isDebugEnabled()) {
460 LOG.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
461 }
462
463 Class type = loader.loadClass(externalName);
464 if (test.matches(type) ) {
465 classMatches.add( (Class<T>) type);
466 }
467 }
468 if (test.doesMatchResource()) {
469 URL url = loader.getResource(fqn);
470 if (url == null) {
471 url = loader.getResource(fqn.substring(1));
472 }
473 if (url != null && test.matches(url)) {
474 resourceMatches.add(url);
475 }
476 }
477 }
478 catch (Throwable t) {
479 if (LOG.isWarnEnabled()) {
480 LOG.warn("Could not examine class '" + fqn + "' due to a " +
481 t.getClass().getName() + " with message: " + t.getMessage());
482 }
483 }
484 }
485 }